import pyglet
from pyglet.gl import *
#from OpenGL.GLUT import *
from pyglet.window import key

#from drawable import Drawable

class Window(pyglet.window.Window):
	"""Window for OpenGL context"""
	def __init__(self, game, caption, width, height, hz):
		
		config = Config(sample_buffers=1, samples=4, depth_size=16, double_buffer=True,)
		try:
			super(Window, self).__init__(resizable=True, config=config)
		except:
			super(Window, self).__init__(resizable=True)
		self.game = game
		self.set_caption(caption)
		self.width = width
		self.height = height
		self._initGL()
		pyglet.clock.schedule_interval(self.update, 1./hz) #rate at which to step

	def update(self, dt):
		self.game.step()

	def on_draw(self):
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);	#Clear screen and depth buffer
		glLoadIdentity()
		self.game.draw()

	def on_resize(self, w, h):
		if h == 0:		#Prevent a /0 if window is too small
	 		  h = 1
		glViewport(0, 0, w, h)		#Reset current viewport and perspective transformation
		glMatrixMode(GL_PROJECTION)
		glLoadIdentity()
		gluPerspective(45.0, float(w)/float(h), 0.1, 1000.0)
		glMatrixMode(GL_MODELVIEW)
		return pyglet.event.EVENT_HANDLED;

	def on_key_press(self, symbol, modifiers):
		if symbol == key.ESCAPE:
			self.dispatch_event('on_close')
		else:
			if not(symbol in self.game.keys):
				self.game.keys.append(symbol)
	
	def on_key_release(self, symbol, modifiers):
		if symbol in self.game.keys:
				self.game.keys.remove(symbol)

	def _initGL(self):
		glClearColor(0.0, 0.0, 0.0, 0.0)	# This Will Clear The Background Color To Black
		glClearDepth(1.0)					# Enables Clearing Of The Depth Buffer
		glDepthFunc(GL_LESS)				# The Type Of Depth Test To Do
		glEnable(GL_DEPTH_TEST)				# Enables Depth Testing
		glShadeModel(GL_SMOOTH)				# Enables Smooth Color Shading
		glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
		glEnable(GL_BLEND);
		glMatrixMode(GL_MODELVIEW)